package com.jian.dao.impl;

import com.jian.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.jetbrains.annotations.NotNull;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Jiange
 * @create 2021-04-06-19:39
 */
public abstract class BaseDAO {
    private QueryRunner queryRunner = new QueryRunner();

    public int update(@NotNull Connection connection, @NotNull String sql, Object...params) throws SQLException {
        int update = queryRunner.update(connection, sql, params);
        return update;
    }

    /**
     * 查询返回一个JavaBean对象的sql语句
     * @param connection
     * @param sql
     * @param type
     * @param params
     * @param <T>
     * @return
     * @throws SQLException
     */
    public <T> T queryForOne(@NotNull Connection connection,@NotNull String sql,Class<T> type,Object...params) throws SQLException {
        System.out.println(connection);
        T query = queryRunner.query(connection, sql, new BeanHandler<T>(type), params);
        return  query;
    }

    /**
     *
     * @param connection
     * @param sql
     * @param type
     * @param params
     * @param <T>
     * @return
     * @throws SQLException
     */
    public <T> List<T> queryForList(@NotNull Connection connection,@NotNull String sql,Class<T> type,Object...params) throws SQLException {
        List<T> query = queryRunner.query(connection, sql, new BeanListHandler<T>(type), params);
        return query;
    }

    /**
     *
     * @param connection
     * @param sql
     * @param params
     * @return
     * @throws SQLException
     */
    public Object queryForSingleValue(@NotNull Connection connection,@NotNull String sql,Object...params) throws SQLException {
        Object query = queryRunner.query(connection, sql, new ScalarHandler<>(), params);
        return query;
    }
}
